<template>
  <van-pull-refresh
      :class="[us.b()]"
      v-model="refreshing"
      @refresh="onRefresh">
    <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad">
      <div v-for="record in config.dataSource" :key="record">
        <slot name="default" :record="record"/>
      </div>
    </van-list>
  </van-pull-refresh>
  <popup-search ref="refPopupSearch"/>
</template>
<script lang="ts" setup>
import PopupSearch from './PopupSearch.vue'
import {useNamespace} from '@/utils';
import {PropType, shallowRef, useSlots} from 'vue';
import {defaultConfig, PageData, RefreshListConfig} from "@hhd/plat/RefreshList/RefreshListType";
import {$loading} from "@plat";

const slots = useSlots();
const us = useNamespace('refresh-list');
const finished = shallowRef(false);
const loading = shallowRef(false);
const refreshing = shallowRef(false);
const refPopupSearch = shallowRef();
const props = defineProps({
  config: {
    type: Object as PropType<RefreshListConfig>,
    default: defaultConfig
  }
})

function getQueryParameter() {
  return {
    ...props.config?.queryParams,
    pageNo: props.config?.page.current,
    pageSize: props.config?.page.pageSize,
  };
}

function loaded() {
  loading.value = false;
  refreshing.value = false;
}

function refreshData() {
  props.config.page.current = 1;
  props.config.page.pageSize = 20;
  finished.value = false;
  let params = getQueryParameter()
  props.config.loadPage(params, (pageData: PageData): void => {
    $loading.stopLoading();
    props.config.page.current = pageData.current;
    props.config.page.pageSize = pageData.size;
    props.config.dataSource = [...pageData.records];
    finished.value = pageData.records.length < props.config.page.pageSize
    loaded()
  })
}

const loadflag = shallowRef(false)

function onLoad() {
  if (loadflag.value) return
  loadflag.value = true;

  props.config.page.current++;
  let params = getQueryParameter()
  props.config.loadPage(params, (pageData: PageData): void => {
    $loading.stopLoading();
    props.config.dataSource.push(...pageData.records);
    finished.value = pageData.records.length < props.config.page.pageSize
    loaded()
    loadflag.value = false;
  })
}

function onRefresh() {
  refreshData();
}

function doPopupSearch() {
  refPopupSearch.value.search({
    config: props.config,
    slots
  });
}

defineExpose({
  popupSearch: doPopupSearch
})
defineOptions({
  name: 'RefreshList'
});
</script>